﻿Imports System.Net.Sockets
Imports System.Net
Imports System.Threading
Imports System.IO
Imports System.Text.Encoding

Public Class MTPServerObj
    Private ipAdd As IPAddress
    Private port As Integer
    Private listener As TcpListener
    Private started As Boolean
    Private handler As Thread
    Private manager As Thread
    Private queue As ConnectionQueue = New ConnectionQueue()
    Dim waiting As ArrayList = New ArrayList()
    Property initialized As Boolean = False

    Public Sub New(ByVal port As Integer)
        Me.port = port
        ipAdd = Dns.GetHostEntry("localhost").AddressList(0)
    End Sub
    Public Sub New()
        Me.port = 1234
        ipAdd = Dns.GetHostEntry("localhost").AddressList(0)
    End Sub
    Public Sub New(ByVal ip As IPAddress, ByVal port As Integer)
        Me.port = port
        ipAdd = ip
    End Sub

    Public Function initialize() As Boolean
        Try
            listener = New TcpListener(ipAdd, Me.port)
            listener.Start()
            started = True
            initialized = True
        Catch ex As Exception
        End Try
        Return initialized
    End Function

    Public Sub start()
        handler = New Thread(AddressOf handlerTask)
        handler.Start()
        manager = New Thread(AddressOf managerTask)
        manager.Start()
    End Sub

    Public Sub close()
        listener.Stop()
        started = False
        handler.Abort()
        manager.Abort()
    End Sub

    Private Sub handlerTask()
        While (started)
            Try
                Dim client As New TcpClient
                Dim t As New Thread(AddressOf processClient)
                client = listener.AcceptTcpClient()
                t.Start(client)
                'client.Close()
            Catch e As Exception
                Exit While
            End Try
        End While
    End Sub

    Private Sub managerTask()
        While (started)
            waiting = queue.findWaiting()
            For Each t As transfer In waiting
                t.beginTransfer()
            Next
            queue.removeFinished()
            Thread.Sleep(1000)
        End While
    End Sub

    Private Sub processClient(ByVal client As TcpClient)
        Dim stream As BinaryReader = New BinaryReader(client.GetStream)
        Dim otherInfo As Byte = stream.ReadByte()
        If (otherInfo < 1) Then
            Dim uID As Integer = 0
            While (queue.contains(uID))
                uID += 1
            End While
            Dim tmpName As String = UTF8.GetString(stream.ReadBytes(256)).Trim(Chr(0))
            Dim tmpConNum As Integer = stream.ReadInt32
            createTransfer(tmpName, tmpConNum, uID)
            Dim str As New NetworkStream(client.Client)
            Dim finfo As New FileInfo(tmpName)
            Dim message(20) As Byte
            Array.Copy(BitConverter.GetBytes(uID), 0, message, 0, 4)
            Array.Copy(BitConverter.GetBytes(finfo.Length), 0, message, 4, 8)
            Dim int As Long = Math.Floor(finfo.Length / tmpConNum)
            Array.Copy(BitConverter.GetBytes(int), 0, message, 12, 8)
            str.Write(message, 0, 20)
            client.Close()
            str.Close()
        Else
            sortClient(stream.ReadInt32, stream.ReadInt32, client)
        End If
    End Sub

    Private Sub createTransfer(ByVal filename As String, ByVal numberConn As Integer, ByVal uID As Integer)
        queue.addTransfer(New transfer(filename, numberConn, uID))
    End Sub

    Private Sub sortClient(ByVal uID As Integer, ByVal orderNum As Integer, ByVal client As TcpClient)
        queue.sortClient(uID, orderNum, client)
    End Sub

End Class
